
import 'package:intl/intl.dart';
import 'package:valovault_reminder/common/bean/val_user_base_info_model.dart';
import 'package:valovault_reminder/common/config/val_assets_name.dart';
import 'package:valovault_reminder/common/config/val_client_url_path.dart';
import 'package:valovault_reminder/common/ui/val_ui_kit_base_colors.dart';
import 'package:valovault_reminder/common/ui/val_ui_kit_dialog_impl.dart';
import 'package:valovault_reminder/common/ui/val_auto_fit_screen_size.dart';
import 'package:valovault_reminder/common/ui/val_common_text.dart';
import 'package:valovault_reminder/common/util/val_app_state_tool.dart';
import 'package:valovault_reminder/http/val_dio_fetch_kit.dart';
import 'package:valovault_reminder/pages/base/val_base_ui_page.dart';
import 'package:valovault_reminder/pages/home/models/val_user_info_base_data.dart';
import 'package:valovault_reminder/pages/notice/components/val_notice_list_body_cell.dart';
import 'package:valovault_reminder/pages/notice/val_notice_config_page.dart';
import 'package:valovault_reminder/pages/notice/val_notice_info_page.dart';
import 'package:valovault_reminder/pages/notice/val_reminder_coin_shop_page.dart';
import 'package:valovault_reminder/util/val_screen_size_kit.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';

import '../../common/ui/val_none_data_view.dart';
import '../../common/util/val_shared_preferences_tool.dart';
import '../../http/val_http_worker.dart';
import '../../util/val_toast_kit.dart';
import '../../util/val_eventbus_manager.dart';
import '../home/components/val_home_delete_alert_view.dart';
import '../home/models/val_post_record_model.dart';
import 'components/val_notice_recharge_alert_view.dart';

class ValNoticeListPage extends StatefulWidget {
  const ValNoticeListPage({super.key});

  @override
  State<ValNoticeListPage> createState() => _ValNoticeListPageState();
}

class _ValNoticeListPageState extends ValBaseUIPageState<ValNoticeListPage> {
  List<ValUserInfoBaseData> userList = [];
  List<String> headerList1 = [];
  List<String> headerList2 = [];
  List<String> headerList3 = [];

  List<String> categoryTypeList = ['Vehicle Maintenance',
    'Insurance Expiry', 'Annual Inspection Due', 'Loan Payment'];
  bool selectedMenu = false;
  List<ValPostRecordModel> _listData = [];
  int freeAmount = 0;
  String userId = 'ID : 1146289';
  int userCoin = 0; //金币数
  String userHeader = '';
  bool disposeState = false;

  @override
  bool get wantKeepAlive => true;

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    isAppBar = false;
    extendBodyBehindAppBar = true;
    bgColor = const Color(0xFF143B42);
    requestAccountInfo();
    // WidgetsBinding.instance.addPostFrameCallback((timeStamp) {
    //   requestUserList();
    // });

    ValEventbusManager.getInstance().eventBus.on().listen((event) {
      if (event.toString() == "coinCharged") {
        requestAccountInfo();
        return;
      }
      if (event.toString() != "postNotice") {
        return;
      }
      saveFreeNoticeAmount();
      loadData();
    });
  }

  @override
  void dispose() {
    // TODO: implement dispose
    disposeState = true;
    super.dispose();
  }

  loadUserInfo() {
    if (disposeState) {
      return;
    }

    if (ValAppStateTool().accountInfo != null) {
      setState(() {
        userCoin = ValAppStateTool().accountInfo!.availableCoins;
        userId = ValAppStateTool().accountInfo!.userId;
        userHeader = ValAppStateTool().accountInfo!.avatarUrl ?? '';
      });
    }
  }

  void onTapCategoryItem(String title, int index) {
    // 次数用完
    if (freeAmount < 1) {
      showRechargeAlertView();
      return;
    }
    pushToNoticeConfigPage(title: title);
    setState(() {
      selectedMenu = false;
    });
  }

  void showRechargeAlertView() {
    ValUIKitDialogImpl.showCenter(ValNoticeRechargeAlertView(() {
      pushToCoinShopPage();
    }, () { //消费
      reviewModeConsume(10, onTapGetCoin: () {
        pushToCoinShopPage();
      });
    }));
  }

  void reviewModeConsume(double outLay, {VoidCallback? onTapGetCoin}) {
    int userCoin = ValAppStateTool().accountInfo!.availableCoins;
    if (outLay > userCoin) {
      if (onTapGetCoin != null) {
        onTapGetCoin();
      }
      return;
    }
    ValHttpWorker.requestCoinCostResource(outlay: outLay, finishCallback: (res) {
      if (res) {
        ValToastKit.showMessage('Success');
        /// 获取用户信息
        ValAppStateTool.getUserInfo(refresh: true, completion: (user) {

        });
        requestAccountInfo();
      }
    });
  }

  ///剩余次数
  void readFreeNoticeAmount() async {
    String userId = ValAppStateTool().accountInfo?.userId ?? "userId";
    freeAmount = await ValLocalStore.getValue("$userId-freeTime", 5);
    setState(() {});
  }

  void saveFreeNoticeAmount() async {
    String userId = ValAppStateTool().accountInfo?.userId ?? "userId";
    await ValLocalStore.saveValue("$userId-freeTime", freeAmount - 1);
  }

  void pushToNoticeInfoPage(ValPostRecordModel listModel) {
    Navigator.push(
      context,
      MaterialPageRoute(builder: (context) {
        return ValNoticeInfoPage(listModel: listModel,);
      }),
    );
  }

  void pushToNoticeConfigPage({String title = '', ValPostRecordModel? data}) {
    Navigator.push(
      context,
      MaterialPageRoute(builder: (context) {
        return ValNoticeConfigPage(categoryTitle: title, listModel: data,);
      }),
    );
  }

  void pushToCoinShopPage() {
    Navigator.push(
      context,
      MaterialPageRoute(builder: (context) {
        return const ValReminderCoinShopPage();
      }),
    );
  }

  ///获取账号信息
  void requestAccountInfo() {
    ValDioFetchKit.getInstance().getJsonWithUrl(ValClientUrlPath.userInfo, {'userId' : ValAppStateTool().userId},
            (data, errorCode, message){
          if (errorCode == 0) {
            ValUserBaseInfoModel user = ValUserBaseInfoModel.fromJson(data);
            ValAppStateTool().accountInfo = user;
            // print('账号信息:${ValAppStateTool().accountInfo?.nickname}');
            loadUserInfo();
            loadData();
          }
        }, (err) {

        });
  }

  Future<void> loadData() async {
    List<ValPostRecordModel> list = await ValPostRecordModel().readCategoryDb('3');
    _listData = list;
    readFreeNoticeAmount();

    setState(() {

    });
  }

  ///获取用户列表
  void requestUserList() {
    var params = {
      "category": "Popular", // 分类固定传Popular
      "isPageMode": true,
      "isRemoteImageUrl": true, // 必须为true 否则返回的头像链接需要拼接
      "limit": 20,
      "page": 1,
      "tag": "All",
    };
    ValUIKitDialogImpl.showProgress();
    ValDioFetchKit.getInstance().postJsonWithUrl(ValClientUrlPath.userList, params, (data, errorCode, message) {
      ValUIKitDialogImpl.hideProgress();
      // print('用户列表:$data');
      if (errorCode == null || errorCode == -2) {
        return;
      }
      int index = 0;
      for(Map<String, dynamic> item in data) {
        ValUserInfoBaseData listModel = ValUserInfoBaseData.fromJson(item);
        userList.add(listModel);
        if (index < 4) {
          headerList1.add(listModel.avatar);
        }
        else if (index < 9) {
          headerList2.add(listModel.avatar);
        }
        else if (index < 14) {
          headerList3.add(listModel.avatar);
        }
        index ++;
      }
      setState(() {});
    }, (err) {
      ValUIKitDialogImpl.hideProgress();
      print('用户列表错误:$err');
    });
  }

  void _showDeleteView(ValPostRecordModel postModel) {
    ValUIKitDialogImpl.showCenter(ValHomeDeleteAlertView(() {
      postModel.deleteDb(postModel);
      loadData();
    }));
  }

  Widget createAlertTextContentElement(String content, {VoidCallback? onTap}) {
    return  GestureDetector(
      onTap: onTap,
      child: Container(
        height: 42,
        margin: const EdgeInsets.only(left: 45, right: 45, bottom: 10),
        padding: const EdgeInsets.only(left: 20, right: 20),
        alignment: Alignment.center,
        decoration: BoxDecoration(
          borderRadius: BorderRadius.circular(20),
          color: Colors.white,
        ),
        child: Text(content,
          style: const TextStyle(color: Colors.black, fontSize: 18, fontWeight: FontWeight.normal), overflow: TextOverflow.ellipsis, maxLines: 1,),
      ),
    );
  }

  @override
  Widget buildBody(BuildContext context) {
    return AnnotatedRegion(
      value: SystemUiOverlayStyle.light,
      child: Stack(
        children: [
          Positioned(
            top: 0, left: 0, right: 0, bottom: 0,
            child: Container(
            decoration: const BoxDecoration(
              gradient: LinearGradient(
                begin: Alignment.topCenter,
                end: Alignment.bottomCenter,
                colors: [
                  Color(0xFF143B42),
                  Color(0xFF080822),
                ],
              ),))
          ),
          Positioned(
            top: 110 + 30,
            left: 0,
            right: 0,
            bottom: ValScreenSizeKit.getBottomBarH(context) + 40,
            child: _listData.isEmpty ? const ValNoneDataView() : ListView.builder(
              padding: const EdgeInsets.only(bottom: 10),
              itemCount: _listData.length,
              itemBuilder: (BuildContext content, int position) {
                ValPostRecordModel data = _listData[position];
                String customFormat = 'yyyy.MM.dd HH:mm';
                String timeValue = '${data.publishDate} ${data.image}';
                DateFormat formatter = DateFormat(customFormat);
                DateTime noticeDate = formatter.parse(timeValue);
                final difference = DateTime.now().difference(noticeDate);

                return GestureDetector(
                  onTap: () {

                  },
                  child: ValNoticeListBodyCell(
                    title: data.coverImage.isEmpty ? data.title : data.coverImage,
                    content: 'Time ${data.publishDate}',
                    subTime: '${difference.inDays} Days',
                    onTap: (){
                      pushToNoticeInfoPage(data);
                    },
                    onTapDelete: (){
                      _showDeleteView(data);
                    },
                    onTapConfig: (){
                      pushToNoticeConfigPage(data: data);
                    },
                  ),
                );
              },
            ),
          ),

          // 商店入口
          Positioned(
            bottom: MediaQuery.of(context).padding.bottom + 25, left: 25, height: 40, width: 116,
            child: GestureDetector(
              onTap: pushToCoinShopPage,
              child: Container(
                alignment: Alignment.centerLeft,
                decoration: const BoxDecoration(
                  image: DecorationImage(
                      image: AssetImage('${ValAssetsName.ASSETS_Message}val_notice_coin_store_ground.png'),
                      fit: BoxFit.fitWidth),
                ),
                child: Container(
                  margin: const EdgeInsets.only(left: 87, bottom: 4),
                  alignment: Alignment.centerLeft,
                  child: Text(userCoin.toString(),
                    style: const TextStyle(color: Colors.black, fontSize: 8, fontWeight: FontWeight.w500), overflow: TextOverflow.clip,),
                ),
              ),
            ),
          ),
          // 弹框
          Positioned(
            top: 0, left: 0, right: 0, bottom: 0,
            child: Stack(
              children: [
                if (selectedMenu)
                  Positioned(
                    top: 0, left: 0, right: 0, bottom: 0,
                    child: GestureDetector(
                      onTap: () {
                        setState(() {
                          selectedMenu = false;
                        });
                      },
                      child: Container(
                        color: !selectedMenu? Colors.transparent : const Color.fromRGBO(0, 0, 0, 0.6),
                      ),
                    )
                ),
                if (selectedMenu)
                  Positioned(
                  top: 64, left: 24, right: 24, height: 406.w,
                  child: Container(
                    alignment: Alignment.topCenter,
                    child: Container(
                        alignment: Alignment.topCenter,
                        decoration: !selectedMenu? const BoxDecoration(
                          color: Colors.transparent,
                        ) : BoxDecoration(
                            color: Colors.transparent,
                            borderRadius:  BorderRadius.circular(24.w),
                            image: const DecorationImage(
                                image: AssetImage('${ValAssetsName.ASSETS_Message}val_notice_more_ground.png'),
                                fit: BoxFit.fill),
                          ),
                        child: Container(
                          alignment: Alignment.topCenter,
                          margin: const EdgeInsets.only(top: 84, bottom: 0),
                          child: Column(
                            crossAxisAlignment: CrossAxisAlignment.center,
                            children: [
                              createAlertTextContentElement('Vehicle Maintenance', onTap: () {
                                onTapCategoryItem('Vehicle Maintenance', 0);
                              }),
                              createAlertTextContentElement('Insurance Expiry', onTap: () {
                                onTapCategoryItem('Insurance Expiry', 1);
                              }),
                              createAlertTextContentElement('Annual Inspection Due', onTap: () {
                                onTapCategoryItem('Annual Inspection Due', 2);
                              }),
                              createAlertTextContentElement('Loan Payment', onTap: () {
                                onTapCategoryItem('Loan Payment', 3);
                              }),
                              // Container(
                              //   margin: const EdgeInsets.only(top: 10),
                              //   height: 32.w,
                              //   child: _buildAddMoreBtn()
                              // )
                            ],
                          ),
                        ),
                      ),
                    ),
                  ),
                Positioned(
                  top: 64, left: 24, right: 24, height: 46.w,
                  child: Container(
                    alignment: Alignment.center,
                    decoration: BoxDecoration(
                      borderRadius: BorderRadius.circular(20),
                      border: Border.all(
                          width: 1, style: BorderStyle.solid,
                          color: selectedMenu ? Colors.transparent : const Color(0xFFE8A229)
                      ),
                    ),
                    child: ValCommonText.oneLine('Reminder Type', 20.w,
                      ValUIKitBaseColors.white,
                      fontWeight: FontWeight.w500,
                      textAlign:  TextAlign.center,),
                  ),
                ),
                Positioned(
                    top: 64, left: 0, right: 44, height: 46.w,
                    child: Container(
                      alignment: Alignment.centerRight,
                      width: 40.w,
                      child: GestureDetector(
                          onTap: () {
                            setState(() {
                              selectedMenu = !selectedMenu;
                            });
                          },
                          child: Image.asset(ValAssetsName.ASSETS_Message + (selectedMenu ? 'val_notice_more_bnt.png' : 'val_notice_more_unselect.png'), width: 30, height: 30)
                      ),
                    ),
                  ),

                Positioned(
                  top: 36, width: 59, right: 29, height: 28,
                  child: Container(
                    padding: const EdgeInsets.only(top: 4),
                    alignment: Alignment.topCenter,
                    width: 40.w,
                    decoration: const BoxDecoration(
                      color: Colors.transparent,
                      image: DecorationImage(
                          image: AssetImage('${ValAssetsName.ASSETS_Message}val_notice_free_tip_ground.png'),
                          fit: BoxFit.fill),
                    ),
                    child: Text('free x $freeAmount',
                      style: const TextStyle(color: Colors.black, fontSize: 10, fontWeight: FontWeight.w600), overflow: TextOverflow.clip,),
                  ),
                ),

                // if (selectedMenu)
                //   Positioned(
                //     top: 376, left: 10, right: 10,
                //     child: Container(
                //       alignment: Alignment.center,
                //       child: SizedBox(
                //           height: 32.w,
                //           child: _buildAddMoreBtn()
                //       ),
                //     ),
                //   ),
              ],
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildAddMoreBtn() {
    return GestureDetector(
        onTap: () {
          setState(() {
            categoryTypeList.add('');
            selectedMenu = false;
          });
        },
        child: Image.asset('${ValAssetsName.ASSETS_Message}val_notice_add_bnt.png', width: 36, height: 36)
    );
  }
}

